<template>
  <div class="public-explain-action app-container">
    <div class="public-explain-top">
      <div v-if="$route.query.action === 'add'">新增</div>
      <div v-else-if="$route.query.action === 'edit'">编辑</div>
      <div v-else-if="$route.query.action === 'detail'">详情</div>
      <div class="action-btn-box" v-if="$route.query.action !== 'detail'">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="handleAdd"
        >确定</el-button>
        <el-button
          plain
          size="mini"
          @click="goBack"
        >取消</el-button>
      </div>
      <div class="action-btn-box" v-else>
        <el-button
          plain
          size="mini"
          @click="goBack"
        >返回</el-button>
      </div>
    </div>
    <div class="public-explain-content">
      <div class="public-explain-left">
        <el-form :model="queryParams" :rules="rules" label-position="top" ref="queryForm">
        <div class="detail-title">关联景区</div>
            <el-form-item label="景区" prop="jingquId">
                <el-select
                  v-model="queryParams.jingquId"
                  placeholder="请选择景区"
                  :disabled="['detail', 'edit'].includes($route.query.action)"
                  clearable
                  filterable
                  size="small"
                  style="width: 500px"
                >
                  <el-option v-for="item in jingQuList" :key="item.value"
                  :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
            </el-form-item>
          <div class="detail-title">导游导览</div>
            <div
              v-for="(item, index) in fileObj"
              :key="item.id"
              class="fileRow">
                <el-form-item
                  required
                  label="文件/景点名称">
                  <el-input
                    :value="item.jingdianName"
                    placeholder="请输入名称"
                    :readonly="$route.query.action === 'detail'"
                    @input="inputChange(index, $event)"
                    clearable
                    size="small"
                    style="width: 500px"
                  >
                  </el-input>
                </el-form-item>
                <el-form-item
                  label="添加附件"
                  required>
                  <el-upload
                      :disabled="$route.query.action === 'detail'"
                      :action="uploadUrl"
                      :before-upload="(file) => handleBeforeUpload(index, file)"
                      :on-success="(response) => handleUploadSuccess(index, response)"
                      :on-error="handleUploadError"
                      :headers="headers"
                      :show-file-list="false"
                    >
                      <el-input
                        :value="item.file"
                        placeholder="添加音频或视频"
                        readonly
                        clearable
                        size="small"
                        style="width: 700px;"
                      >
                    </el-input>
                  </el-upload>
                </el-form-item>
                <div class="actionIcon" v-if="$route.query.action !== 'detail'">
                  <div class="add" @click="addFileObj">
                    <i class="el-icon-plus"></i>
                    点击添加下一个
                  </div>
                  <div class="delete" v-if="fileObj.length > 1" @click="deleteFileObj(item.id)">
                    <i class="el-icon-minus"></i>
                    删除
                  </div>
                </div>
            </div>
        </el-form>
      </div>
    </div>

  </div>
</template>

<script>
import { updateFn, add, getDetail } from "@/api/form/explain";
import { dictFn } from "@/api/common";
import { getToken } from "@/utils/auth";
import {
  jingQuListApi, // 获取所有景区列表
} from "@/api/YApi/scenicSpot";

export default {
  name: "Logininfor",
  data() {
    return {
      rules: {
          jingquId: [
            { required: true, message: '请选择景区', trigger: 'change' }
          ],
      },
      // 遮罩层
      loading: true,
      uploadUrl: window.serverAPI.url + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      jingQuList: [],
      fileObj: [{
        id: Math.random() + '',
        jingdianName: '',
        file: '',
        fileName: '',
      }],
      statusOptions: [{
        label: '1', value: 1
      }],
      // 导出遮罩层
      exportLoading: false,
      // 查询参数
      queryParams: {
        jingquId: undefined,
      }
    };
  },
  created() {
    let {id} = this.$route.query
    id && this.getDetailFn(Number(id))
    this.getJingQuList()
  },
  methods: {
    inputChange (index, e) {
      // console.log(index, e);
      let obj = this.fileObj[index]
      obj = {
        ...obj,
        jingdianName: e,
      }
      this.$set(this.fileObj, index, obj)
    },
    // 景区详情
    getDetailFn(id) {
      this.queryParams.jingquId = id
      getDetail(id)
        .then((res) => {
          if (res.code === 200) {
            let arr = (res?.data || [])
            if (arr.length) {
              this.fileObj = arr.map(item => {
                return {
                  id: Math.random() + '',
                  jingdianName: item.jingdianName,
                  file: item.jingdianFile,
                }
              })
            }
          }
        })
    },
    // 景区列表
    getJingQuList() {
      jingQuListApi()
        .then((res) => {
          if (res.code === 200) {
            this.jingQuList = res.data.map((v) => {
              return {
                value: v.jingquId,
                label: v.jingquName,
              };
            });
          }
        })
    },
    // 使用 before-upload 限制用户上传的图片格式和大小。
    handleBeforeUpload(index, file) {
      // console.log(file);
      // 校检文件大小
      // const isLt = file.size / 1024 / 1024 < 80;
      // if (!isLt) {
      //   this.$message.error(`上传文件大小不能超过80MB!`);
      //   return false;
      // }
      // // 检验格式
      // let type = file.type;
      // // let arr = ['']
      // let jpg = type.indexOf("jpg");
      // let png = type.indexOf("png");
      // let jpeg = type.indexOf("jpeg");
      // if (jpg == -1 && png == -1 && jpeg == -1) {
      //   this.$message.error(`上传文件格式为jpg，png，jpeg!`);
      //   return false;
      // }

      return true;
    },
    // eventFn(index, duration, response) {
    // },
    // 文件上传成功钩子
    handleUploadSuccess(index, response) {
      if (response.code === 200) {
      let { url, fileName } = response.data;
      let obj = this.fileObj[index]
      obj = {
        ...obj,
        file: url,
        fileName,
      }
      console.log(obj);
      this.$set(this.fileObj, index, obj)
        //经测试，发现audio也可获取视频的时长
        // let audioElement = new Audio(response.data.url);
        // let that = this;
        // function fun (duration) {
        //   that.eventFn(index, duration, response)
        // }
        // audioElement.addEventListener("loadedmetadata", function (_event) {
        //   let duration = audioElement.duration;
        //   fun(duration)
        // });
      }
    },
    // 文件上传失败
    handleUploadError() {
      this.$message.error("图片插入失败");
    },
    handleAdd() {
      this.$refs.queryForm.validate((tag, e) => {
        console.log(tag, e);
        if (tag) {
          let jingdianFiles = []
          let jingdianNames = []
          this.fileObj.forEach(item => {
            jingdianFiles.push(item.file)
            jingdianNames.push(item.jingdianName)
          })
          console.log(jingdianNames);
          console.log(jingdianFiles);
          let fun = this.$route.query.id ? updateFn : add
          fun({
            ...this.queryParams,
            jingdianFiles,
            jingdianNames,
          }).then(res => {
            if (res?.code === 200) {
              this.msgSuccess("保存成功");
              this.goBack();
            } else {
              this.$message.error(res?.msg);
            }
          })
        }
      });
    },
    goBack() {
      this.$router.go(-1);
    },
    addFileObj() {
      console.log(this.fileObj);
      this.fileObj.push({
        id: Math.random() + '',
        jingdianName: '',
        file: '',
      })
    },
    deleteFileObj(id) {
      this.fileObj = this.fileObj.filter(item => item.id !== id);
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.public-explain-action {
  .public-explain-top {
    border-bottom: 1px solid #F2F3F5;
    display: flex;
    justify-content: space-between;
    padding: 12px;
    align-items: center;
    background-color: #ffffff;
  }
  .fileRow {
    background-color: #ffffff;
    width: 100%;
    display: flex;
    >* {
      margin-right: 20px;
    }
  }
  .public-explain-content {
    .public-explain-left {
      width: 100%;
      background-color: #ffffff;
      ::v-deep .el-form-item {
        padding-left: 10px;
      }
    }
    display: flex;
    .detail-title {
      background-color: #ffffff;
      position: relative;
      padding-left: 22px;
      padding-block: 20px;
      &::after {
        content: '';
        width: 4px;
        height: 16px;
        background: #3370FF;
        position: absolute;
        left: 10px;
        top: 0;
        bottom: 0;
        margin: auto 0;

      }
    }
  }
  .actionIcon{
    display: flex;
    color: #3370FF;
    padding-top: 50px;
    >div{
      cursor: pointer;
      white-space: nowrap;
    }
    .delete {
      color: #F54A45;
      margin-left: 20px;
    }
  }
}
</style>
